﻿//////////////////////////////////////////////////////////////////
//
// ScriptFile.cs
//
// Copyright (c) 2012 Dan Pike.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Interfaces;
using Utilities;
using System.IO;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Diagnostics;

namespace ScriptCS
{
   /// <summary>
   /// An implementation based on Microsoft.CSharp
   /// </summary>
   public class ScriptFile : IScriptFile, ScriptInterfaces.IScriptWorld
   {
      private static Logger logger_;
      private string displayName_;
      private string filename_;
      
      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// 
      /// </summary>
      public ScriptFile()
      {
         logger_ = Program.logger;
      }

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Implementation of IScriptFile
      /// </summary>
      public string displayName
      {
         get { return displayName_; }
         set { displayName_ = value; }
      }

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Implementation of IScriptFile
      /// </summary>
      public string filename
      {
         get { return filename_; }
         set { filename_ = value; }
      }

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Implementation of IScriptFile
      /// </summary>
      public bool compile(string filename)
      {
         try
         {
            string providerType = Program.settings.providerType;
            CodeDomProvider provider = CodeDomProvider.CreateProvider(providerType);
            if (null == provider)
            {
               logger_.errorFormat("failed to compile strip, could not find a provider for '{0}'", providerType);
               return false;
            }

            CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateExecutable = false;
            parameters.OutputAssembly = string.Concat(filename, ".script.dll");
            parameters.GenerateInMemory = false;
            parameters.IncludeDebugInformation = true;

            // Include all of the configured dependencies
            Program.settings.dependencies.OfType<Config.Dependency>().ToList()
               .ForEach(dependency => parameters.ReferencedAssemblies.Add(dependency.name));

            // Now we can compile the script
            logger_.debugFormat("parsing script file '{0}'", filename);
            CompilerResults result = provider.CompileAssemblyFromFile(parameters, filename);
            if (result.Errors.HasErrors)
            {
               logger_.debugFormat("failed to parse script file '{0}'", filename);
               result.Errors.OfType<CompilerError>().ToList()
                  .ForEach(error => logger_.debugFormat("   {0}", error.ToString()));
               return false;
            }
            logger_.debugFormat("script file '{0}' compiled OK", filename);
            filename_ = filename;
            return true;
         }
         catch (System.Exception ex)
         {
            logger_.exception(ex);
         }
         return false;
      }

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Implementation of IScriptFile
      /// </summary>
      public object initialize(object entity)
      {
         try
         {

         }
         catch (System.Exception ex)
         {
            logger_.exception(ex);
         }
         return null;
      }

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Implementation of IScriptFile
      /// </summary>
      public bool run(object runner, string methodName, object[] parameters)
      {
         try
         {

         }
         catch (System.Exception ex)
         {
            logger_.exception(ex);
         }
         return false;
      }

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Implementation of IScriptWorld
      /// </summary>
      /// <param name="format"></param>
      /// <param name="args"></param>
      public void logger(int logLevel, string format, params string[] args)
      {
         try
         {
            StackTrace stackTrace = new StackTrace(true);
            StackFrame stackFrame = stackTrace.GetFrame(1);

            MethodBase methodBase = stackFrame.GetMethod();
            logger_.rawFormat(methodBase.DeclaringType.Name, methodBase.Name,
               (Logger.StreamType)logLevel, stackFrame.GetFileName(),
               stackFrame.GetFileLineNumber(), format, args);
         }
         catch (System.Exception ex)
         {
            logger_.exception(ex);
         }
      }
   }
}
